package com.wanmait.movie;

import com.wanmait.movie.interceptor.InitInterceptor;
import com.wanmait.movie.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Resource
    private JWTInterceptor jwtInterceptor;
    @Resource
    private InitInterceptor initInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                .excludePathPatterns("/manage/login")
                .excludePathPatterns("/web/login")
                .excludePathPatterns("/web/register")
                // 上传和访问图片不需要验证token
                .excludePathPatterns("/upload/*")
                .excludePathPatterns("/uploadImages/*")
                .excludePathPatterns("/manage/cinema/uploadPicture")
                .excludePathPatterns("/common/uploadPicture");
    }

    //配置跨域资源共享策略
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                //.allowedMethods("GET","POST","OPTIONS")
                .allowedMethods("*")
                .allowedHeaders("*")
                //.allowCredentials(true)如果设为true 可以传cookie信息，这样session也就能使用，需要客户端配合设置xhr.withCredentials=true
                .maxAge(60*60*2);//单位秒，2个小时内对于复杂请求不用再次发送预检请求
    }

    /**
     * 设置静态资源映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 设置上传的文件静态资源映射，application 里的 mvc 里也要设置下静态目录
        registry.addResourceHandler("/upload/**","/uploadImages/**")
                .addResourceLocations("classpath:/upload/", "file:upload/","classpath:/uploadImages/", "file:uploadImages/");
    }
}
